package com.yunfeisoft.common.session;

import com.yunfeisoft.common.session.UserSession;

import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Jackie Liu on 2017/4/3.
 */
public class ServletSession implements UserSession {

    public static final String USER_SESSION_KEY = "_user_session_key_";
    public static final String VERIFY_CODE_KEY = "_verify_code_key_";
    //private static final ConcurrentHashMap<String, Set<String>> USER_TOKEN_MAP = new ConcurrentHashMap<>();

    @Override
    public boolean storageSessionModel(SessionModel sessionModel) {
        HttpSession session = SpringServletHelper.getRequest().getSession();
        session.setAttribute(USER_SESSION_KEY, sessionModel);
        return true;
    }

    @Override
    public SessionModel getSessionModel() {
        HttpSession session = SpringServletHelper.getRequest().getSession();
        SessionModel sessionModel = (SessionModel) session.getAttribute(USER_SESSION_KEY);
        return sessionModel;
    }

    @Override
    public boolean removeSession() {
        HttpSession session = SpringServletHelper.getRequest().getSession();
        if (session == null) {
            return true;
        }
        SessionModel sessionModel = (SessionModel) session.getAttribute(USER_SESSION_KEY);
        if (sessionModel != null) {
            session.removeAttribute(USER_SESSION_KEY);
        }
        session.invalidate();
        return true;
    }

    @Override
    public void resetSessionTime() {
        //do something
        //在web.xml中配置即可
    }

    @Override
    public void setVerifyCode(String verifyCode) {
        HttpSession session = SpringServletHelper.getRequest().getSession();
        session.setAttribute(VERIFY_CODE_KEY, verifyCode);
    }

    @Override
    public String getVerifyCode() {
        HttpSession session = SpringServletHelper.getRequest().getSession();
        Object value = session.getAttribute(VERIFY_CODE_KEY);
        return value == null ? null : (String) value;
    }
}
